package servletAction;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.DAOAddress;
import dao.DAOContact;
import domain.Address;

/**
 * Servlet implementation class newContact
 */
public class NewContact extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public NewContact() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		String firstname = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
		String email = request.getParameter("email");
		String street = request.getParameter("street");
		String city = request.getParameter("city");
		String zip = request.getParameter("zip");
		String country = request.getParameter("country");

		if(id == "" || firstname == "" || lastName == "" || email == "" ){
			response.sendRedirect("addContact.jsp");
			return;
		}
		if(street == "" || city == "" || zip == "" || country == "" ){
			response.sendRedirect("addContact.jsp");
			return;
		}
		try{
			//long id_int = Integer.parseInt(id);
			DAOContact dao = new DAOContact();
			/*DAOAddress daoA = new DAOAddress();
			Address address = daoA.addAddress(street, city, zip, country);
			*/
			Address address = new Address();
			address.setStreet(street);
			address.setCity(city);
			address.setZip(zip);
			address.setCountry(country);
			
			if(dao.addContact(new Long(0), firstname, lastName, email,address,null)){
				RequestDispatcher rd = request.getRequestDispatcher("/menu.jsp");
				rd.forward(request, response);
			}else{
				response.sendRedirect("addContact.jsp");
				return;
			}
		}catch (Exception e) { 
			response.sendRedirect("addContact.jsp");
			return;
		}
	}
}
